/**
 * Created by Yieong on 14-9-11.
 */
;

(function($){
    var tables      = new Object(),
        callback    = new Object();

    var counter = 0,
        defaultLength  = 50,
        pageBtnCnt = 7,
        ajaxLoading = false;

    $.fn.gridExt = {
        "sortRule" : {}
    }

    $.fn.setGridCallback = function(key, func){
        var id = this.attr('id');

        if(id && func){
            if(!callback[id]) callback[id] = { };
            callback[id][key] = func;
        }
    }


    $.fn.grid = function(config){
        var id = this.attr('id');

        if(id){
            id = '__t_' + id;
        }else{
            id = '__t_' + counter++;
        }

        if(typeof config != 'object') config = $.parseJSON(config);

        if( config.url ){
            var isAjax = true;
        }else{
            var isAjax = false;
            config['data'] = obj2Arr(config['data']);
        }

        tables[id] = {
            'id'     : id,
            'object' : this,
            'config' : config,
            'isAjax' : isAjax
        };

        // 将配置缓存起来
        this.addClass('once-table-div');

        init(id);
    };

    // 建立表单
    var init  = function(id){
        var object = tables[id]['object'],
            config = tables[id]['config'],
            id     = tables[id]['id'];

        object.html('<div class="once-main-table-div"><table id="'+id+'" class="once-table once-main-table"><thead></thead><tbody></tbody></table></div>' +
            '<div class="once-page clearfix"><ul class="clearfix"></ul><p></p></div>');

        if(typeof config['params'] != 'undefined') $('#'+id).data('params', config['params']);

        // 如果有初始排序，则进行初始排序
        if(config['setting']['order']){
            sortData(id, config['setting']['order']);
        }

        buildThead(id);
        buildTbody(id);

        object.find('.once-fix-column-table tr, .once-main-table tr').live('mouseenter', function(){
            object.find('.once-fix-column-table tbody tr:eq('+$(this).index()+'), .once-main-table tbody tr:eq('+$(this).index()+')').addClass('hover');
        }).live('mouseleave', function(){
            object.find('.once-fix-column-table tbody tr:eq('+$(this).index()+'), .once-main-table tbody tr:eq('+$(this).index()+')').removeClass('hover');
        });
    }

    // 加载thead
    var buildThead = function(id){
        var object      = tables[id]['object'],
            config      = tables[id]['config'],
            order       = config['setting']['order'],
            header      = tables[id]['config']['header'],
            headerHtml  = special2Html(header.html),
            thead       = object.find('.once-table thead');

        thead.html(headerHtml);
        if(order && order[0]){
            thead.find('.order.enable[key="'+order[0]+'"] i').removeClass('icon-order-hover').addClass('icon-order-'+(order[1] || 'asc'));
        }

        // 排序按钮
        thead.find('.order.enable').click(function(){
            var iClass = ($(this).find('i').hasClass('icon-order-desc')) ? 'asc' : 'desc',
                ths = object.find('th'),
                th = ths.filter('[key="'+$(this).attr('key')+'"]');

            ths.find('i').removeClass('icon-order-asc icon-order-desc').addClass('icon-order-hover');

            th.find('i').removeClass('icon-order-hover').addClass('icon-order-' + iClass);

            config['setting']['order'] = [$(this).attr('key'), iClass];
            //console.log(id);
            //console.log(config['setting']['order']);
            sortData(id, config['setting']['order']);
            buildTbody(id);

            if(typeof callback[id] !== 'undefined' && typeof callback[id]['sort'] !== 'undefined'){
                callback[id]['sort']();
            }
        });
    }

    // 加载tbody
    var buildTbody = function(id){
        var thisTable   = tables[id],
            object      = thisTable['object'],
            isAjax      = thisTable['isAjax'],
            config      = thisTable['config'],
            header      = config['header']['info'],
            length      = config['setting']['length'] || defaultLength,
            page        = thisTable['page'] || config['setting']['page'] || 1,
            showAll     = config['setting']['showAll'] || false;

        // tableData 表示表单展示的数据
        var tableData = [];

        // ----- 异步表单取数据 -----
        if(isAjax){
            if(ajaxLoading){
                alert('Loading..');
            }else{
                //ajaxLoading = true;

                var url = config['url'];

                $("#"+id).css('height', $("#"+id).outerHeight() + 'px');
                object.find('.once-main-table tbody').html('<tr><td colspan="'+header.length+'"><div style="text-align: center; font-size: 14px; line-height: 18px;"><img src="/public/static/images/loading.gif">&nbsp;&nbsp;loading...</div></td></tr>');
                object.find('.once-fix-column-div').hide();

                var getArgs = { order:config['setting']['order'] };
                if(!showAll){
                    getArgs.page = page;
                    getArgs.length = length;
                }

                $.getJSON(url, getArgs, function(result){
                    ajaxLoading = false;

                    if(result) result.data = obj2Arr(result.data);

                    // 如果有数据，则展示数据
                    if(result && result.result && result.data && result.data.length > 0){

                        // 数据展示
                        buildData(object, header, result.data, result.total);
                        buildPage(id, result.count, length, page);
                        fixTable(id);
                        object.find('.once-fix-column-div').show();
                        // 否则提示没有数据
                    }else{
                        var msg = (result && result.msg) ? result.msg : '<i class="fa fa-inbox"></i>&nbsp;&nbsp;暂时没有数据';
                        object.find('.once-table tbody').html('<tr><td colspan="'+header.length+'" style="color:#999; text-align: center; ">'+msg+'</td></tr>');
                        object.find('.once-fix-column-div').show();
                    }

                });
            }

        // ----- 同步表单取数据 -----
        }else{
            var data = config['data'],
                total = config['total'];

            if(showAll){
                var i= 0, j = 10000;
            }else{
                var i = (page - 1) * length,
                    j = length;
            }

            for(; j>0; i++, j--){
                if(i >= data.length){
                    break;
                }
                tableData.push(data[i]);
            }

            // 数据展示
            if(total){
                // 第一页则显示小计
                buildData(object, header, tableData, total);
            }else{
                buildData(object, header, tableData);
            }

            if(!showAll) buildPage(id, data.length, length, page);
            fixTable(id);
        }
    }

    // 加载表单数据
    var buildData = function(object, header, data, total){
        var bodyHtml = '';

        var orderColumns = object.find('.icon-order-asc,.icon-order-desc').parent().attr('key');

        // 显示小计
        if(total){
            var totalHtml = ''
            for(var l in header){
                var tdData = total[header[l]['key']] || '';

                totalHtml += buildHtml('td', special2Html(tdData), {
                    "key" : header[l]['key'],
                    "class" : 'total ' + ((header[l]['key'] == orderColumns) ? '1' : '2'),
                    "nowrap" : "nowrap"
                });
            }
            bodyHtml += buildHtml('tr', totalHtml);
        }

        if(data.length > 0 || bodyHtml.length > 0){
            for(var k in data){
                var trHtml = ''
                for(var l in header){

                    var tdData = data[k][header[l]['key']];
                    if(!tdData && tdData != 0){
                        tdData = '';
                    }

                    trHtml += buildHtml('td', special2Html(tdData), {
                        "key" : header[l]['key'],
                        "class" : (header[l]['key'] == orderColumns) ? '1' : '2',
                        "nowrap" : "nowrap"
                    });
                }
                bodyHtml += buildHtml('tr', trHtml);
            }
            object.find('.once-table tbody').html(bodyHtml);
        }else{
            var msg = '<i class="fa fa-inbox"></i>&nbsp;&nbsp;暂时没有数据';
            object.find('.once-table tbody').html('<tr><td colspan="'+header.length+'" style="color:#999; text-align: center; ">'+msg+'</td></tr>');
        }
    }

    // 加载分页插件
    var buildPage = function(id, count, pageSize, currentPage){
        var thisTable   = tables[id],
            object      = thisTable['object'],
            count       = parseInt(count),
            pageCnt     = Math.ceil(count / pageSize), // 总页数
            pageDiv     = object.find('.once-page'),
            pageUl      = pageDiv.find('ul'),
            pageP       = pageDiv.find('p'),
            list        = [];


        // 分页页码
        var pageArr = [10, 20, 40, 50, 60, 80, 100, 150, 200];

        var pageSelect = '<select class="once-top-page-size">';
        for(var i in pageArr){
            pageSelect += '<option value="'+pageArr[i]+'"';
            if(pageArr[i] === pageSize) pageSelect += ' selected="selected" ';
            pageSelect += '>'+pageArr[i]+'</option>'
        }
        pageSelect += '</select>';

        // 加入分页文本
        var text = '[#currentPage#/#pageCnt#] 共 #count# 条数据，每页 #pageSize# 条';
        text = text.replace('#count#', count)
                .replace('#pageSize#', pageSelect)
                .replace('#currentPage#', currentPage)
                .replace('#pageCnt#', pageCnt)
        pageP.html(text);

        
        // 选择页码点击动作
        pageP.find(".once-top-page-size").change(function(){
            thisTable['config']['setting']['length'] = parseInt($(this).attr('value'));
            thisTable['page'] = 1;
            buildTbody(id);
            buildPage(id, count, config['setting']['length'], 1);
        });

        if(pageCnt > 0){
            list.push({
                'text': '<<',
                'value': 1,
                'class': 'top_page top_enable_page'
            });

            list.push({
                'text': '上一页',
                'value': currentPage - 1,
                'class': (currentPage > 1) ? 'top_page top_enable_page' : 'top_page'
            });

            var beginPage = (pageCnt - currentPage > 3) ? currentPage - 3 : currentPage - 6 + (pageCnt - currentPage);
            if(beginPage < 1) beginPage = 1;

            for(var i=0; i<pageBtnCnt; i++){
                var thePage = beginPage+i;

                list.push({
                    'text': thePage,
                    'value': thePage,
                    'class': (thePage == currentPage) ? 'top_page top_current_page' : 'top_page top_enable_page'
                });

                if(thePage >= pageCnt) break;
            }

            list.push({
                'text': '下一页',
                'value': currentPage + 1,
                'class': (currentPage + 1 > pageCnt) ? 'top_page' : 'top_page top_enable_page'
            });

            list.push({
                'text': '>>',
                'value': pageCnt,
                'class': 'top_page top_enable_page'
            });
        	
	        // 加入分页按钮
	        pageUl.children().remove();
	        for(var i in list){
	            pageUl.append(buildHtml('li', buildHtml('a', list[i]['text'], {
	                'value' : list[i]['value'],
	                'href'  : 'javascript:;',
	                'class' : list[i]['class']
	            })));
	        }
	
	        // 分页按钮点击动作
	        pageUl.find(".top_enable_page").click(function(){
	            thisTable['page'] = parseInt($(this).attr('value'));
	            buildTbody(id);
	        });
        }
    }

    // 建立HTML标签
    var buildHtml = function(tag, value, attr){
        var html = '<' + tag;
        for(var i in attr){
            html += ' ' + i + '="' + attr[i] + '"';
        }
        html += '>' + value;
        html += '</' + tag + '>';
        return html;
    }

    // 表单锁定
    var fixTable = function(id){
        var config = tables[id]['config'],
            setting = config['setting'] || {},
            fix = setting['fix'];

        if(fix){
            if(fix.row){
                fixTableHeader(id);
            }

            if(fix.col){
                fixTableColumn(id, fix.col);
            }
        }
    }

    // 锁定表头
    var fixTableHeader = function(id){
        var table = tables[id],
            object = table.object;

        // 如果该表单没有生成锁表头的元素，则先构造
        if(object.find(".once-fix-header-table").length < 1){
            var thead = object.find('thead'),
                thead_clone = thead.clone(true);

            $('<div class="once-fix-header-div"><table class="once-fix-header-table once-table"></table></div>').appendTo(object).css({
                "margin": 0,
                "padding": 0,
                "position": "absolute",
                "top": 0,
                "left": 0,
                "z-index": 2
            });

            object.find(".once-fix-header-table").append(thead_clone);

            // 竖向滚动时判断是否锁定表头
            var mainTable = object.find('.once-main-table'),
                fixDiv = object.find('.once-fix-header-div');
            $(window).scroll(function(){
                var windowScroll = $(this).scrollTop(),
                    mainTop = mainTable.offset().top;
                if(windowScroll > mainTop && windowScroll < (mainTop + mainTable.innerHeight())){
                    fixDiv.css('top', windowScroll-mainTop);
                    object.find('.once-fix-both-div').css('top', windowScroll-mainTop);
                }else{
                    fixDiv.css('top', 0);
                    object.find('.once-fix-both-div').css('top', 0);
                }
            });
            object.find('.once-main-table-div').scroll(function(){
                fixDiv.css('left', 0 - $(this).scrollLeft());
            });
        }

        // 根据当前表头，计算锁定行每一列的宽度
        var th = object.find('.once-main-table th'),
            th_clone = object.find('.once-fix-header-table th');


        object.find(".once-fix-header-table").css({
            'width': object.find('thead').width() + 1
        });

        th.each(function(i){
            th_clone.eq(i).css('width', $(this).width() + parseInt($(this).css('border-left-width')));
        });
    }

    // 锁定列
    var fixTableColumn = function(id, cols){
        var table = tables[id],
            object = table.object;

        // 如果该表单没有生成锁表头的元素，则先构造
        if(object.find(".once-fix-column-table").length < 1){

            $('<div class="once-fix-column-div"><table class="once-fix-column-table once-table"></table></div>').appendTo(object).css({
                "margin": 0,
                "padding": 0,
                "position": 'absolute',
                "top": object.find('.once-main-table').position().top + object.find('.once-main-table thead').outerHeight(),
                "left": 0,
                "z-index": 1
            });

            $('<div class="once-fix-both-div"><table class="once-fix-both-table once-table"></table></div>').appendTo(object).css({
                "margin": 0,
                "padding": 0,
                "position": 'absolute',
                "top": 0,
                "left": 0,
                "z-index": 3
            });
        }

        var clone_fix_column_table = object.find(".once-fix-column-table"),
            clone_fix_both_table = object.find(".once-fix-both-table");

        // 锁左边的 cols 列
        clone_fix_column_table.children().remove();
        object.find('.once-main-table tbody tr').each(function(i){
            var tr = $('<tr></tr>');

            $(this).children(":lt("+cols+")").each(function(){
                var td_clone = $(this).clone(true);
                td_clone.css('width', $(this).width() + parseInt($(this).css('border-left-width')));
                tr.append(td_clone);
            });

            tr.css('height', $(this).height() + parseInt($(this).css('border-width')));

            clone_fix_column_table.append(tr);
        });

        // 生成左上角的固定栏
        clone_fix_both_table.children().remove();
        var tr1 = $('<tr></tr>'),
            tr2 = $('<tr></tr>');
        var col_sum = 0, tr2_cnt = 0;
        object.find('.once-main-table thead tr:first-child th:lt('+cols+')').each(function(i){
            var td_clone = $(this).clone(true);

            td_clone.css({
                "width": $(this).width() + parseInt($(this).css('border-left-width')),
                "height": $(this).height() + parseInt($(this).css('border-top-width'))
            });

            tr1.append(td_clone);

            // 计算第二行表头需要取多少列
            var colspan = parseInt($(this).attr('colspan'));
            if(colspan > 1){
                tr2_cnt += colspan;
            }
            col_sum += colspan;
            if(col_sum >= cols){
                return false;
            }
        });
        clone_fix_both_table.append(tr1);

        // 生成左上角的第二个固定栏
        if(tr2_cnt > 0){
            object.find('.once-main-table thead tr:last-child th:lt('+tr2_cnt+')').each(function(i){
                var td_clone = $(this).clone(true);

                td_clone.css({
                    "width": $(this).width() + parseInt($(this).css('border-left-width')),
                    "height": $(this).height() + parseInt($(this).css('border-top-width'))
                });

                tr2.append(td_clone);
            });

            clone_fix_both_table.append(tr2);
        }
    }

    // 获得排序数据
    var getSortData = function(id, key, rule){
        var config = tables[id]['config'],
            specialKey = getSpecialSortKey(key),
            ruleArr = rule.split(","),
            funcArr = [];

        for(var i in ruleArr){
            var oneFunc = $.fn.gridExt.sortRule[ruleArr[i]];
            if(oneFunc && (typeof oneFunc === 'function')){
                funcArr.push(oneFunc);
            }
        }

        for(var j in config.data){
            if(typeof config.data[j][specialKey] !== 'undefined')
                break;

            var value = config.data[j][key];
            if(value){
                for(var k in funcArr){
                    value = funcArr[k](special2Html(value));
                }
            }
            config.data[j][specialKey] = value;
        }
    }

    // 设置排序
    var sortData = function(id, sort){
        var config = tables[id]['config'],
            info = config.header.info;

        var rule;
        for(var i in info){
            if(!info[i].UnSort && info[i].key === sort[0]){
                var rule = rule || info[i].rule || false;
            }
        }

        // 根据传入的参数进行排序
        var compare = function (column, order) {
            var flag   = (order == 'asc') ? 1 : -1;

            return function (obj1, obj2) {
                var val1 = obj1[column] || 0;
                var val2 = obj2[column] || 0;

                if ((typeof val2 != 'undefined') && val1 < val2) {
                    return -1 * flag;
                } else if ((typeof val1 != 'undefined') && val1 > val2) {
                    return 1 * flag;
                } else {
                    return 0;
                }
            }
        }

        if(typeof rule === 'undefined'){
            return false; // 没有匹配到要排序的Key
        } else if(rule !== false && $.fn.gridExt.sortRule){
            getSortData(id, sort[0], rule);
            var column = getSpecialSortKey(sort[0]);
        } else{
            var column = sort[0];
        }
        var r = GetQueryString('r');
        if(r == 'everyGrade/grade'){  //实时等级流失排序
        	var flag   = (sort[1] == 'asc') ? 1 : -1;
        	function sequence(a,b){
        		var ab = Number(a[column].replace("%","")) - Number(b[column].replace("%",""));
        		return ab * flag;
        		//return (a[column] - b[column]) * flag;
        	}
        	config['data'].sort(sequence);
        }else{
        	//console.log(1);
        	if(config['data']) config['data'].sort(compare(column, sort[1]));
        }
        
    }

    // 对象转数组
    var obj2Arr = function(the){
        // 如果data是对象，则转成数组
        if( Object.prototype.toString.apply(the) === '[object Object]'){
            var arr = [];
            for(var i in the){
                arr.push(the[i]);
            }
            return arr;
        }else{
            return the;
        }
    }

    var special2Html = function(the){
        if(typeof the === 'string'){
            the = the.replace(/&amp;/g,"&")
                .replace(/&lt;/g,"<")
                .replace(/&gt;/g,">")
                .replace(/&quot;/g,"\"");

            return the;
        }else{
            return the;
        }
    }

    var getSpecialSortKey = function(key){
        return '__sort_'+key;
    }

}) ( jQuery );

/**
 * 获取参数值
 * as:GetQueryString("r");
 * @param {Object} name
 */
function GetQueryString(name){
     var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
     var r = window.location.search.substr(1).match(reg);
     if(r!=null)return  unescape(r[2]); return null;
}
